package cn.thinkluck.pattern.prototype.deep;

import lombok.Data;
import org.springframework.util.SerializationUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 播放列表
 * 序列化深拷贝示例
 */
@Data
public class Playlist2 implements Serializable {
    private Long id;
    private String name;
    private List<Song> songs = new ArrayList<>();

    public Playlist2() {
    }

    //序列化深拷贝播放列表
    @Override
    public Playlist2 clone() {
        //序列化
        byte[] bytes = SerializationUtils.serialize(this);
        //反序列化
        return (Playlist2) SerializationUtils.deserialize(bytes);
    }

    //深拷贝播放列表
    public Playlist2(Playlist2 sourcePlayList) {
        this.id = sourcePlayList.getId();
        this.name = sourcePlayList.getName();
        this.songs = sourcePlayList.getSongs();
    }


    public static void main(String[] args) {
        Playlist2 playlist = new Playlist2();
        playlist.setId(1L);
        playlist.setName("杰伦");
        playlist.songs.add(new Song("稻香", "杰伦"));
        playlist.songs.add(new Song("迷迭香", "杰伦"));
        playlist.songs.add(new Song("七里香", "杰伦"));
        // 浅拷贝后的最喜爱的专辑
        Playlist2 favouriteList = playlist.clone();
        favouriteList.songs.add(new Song("曹操", "林俊杰"));
        System.out.println(favouriteList);
        //可以看到深拷贝后的最喜爱的专辑和原专辑的歌单不是同一个对象
        System.out.println(playlist.id==favouriteList.id);
        System.out.println(playlist.name==favouriteList.name);
        System.out.println(playlist.songs.get(0));
        System.out.println(favouriteList.songs.get(0));
    }
}
